const Koa = require('koa');
const Router = require('koa-router');
const staticCache = require('koa-static-cache');
const body = require('koa-better-body');
const convert = require('koa-convert');
const session = require('koa-session');
const pathlib = require('path');
const ejs = require('koa-ejs');
const config = require('./config');
const error = require('./lib/error.js');
const loglib = require('./log/log');
const db = require('./lib/db');  // 连接数据库

const server = new Koa();
server.listen(config.port);

// 最顶层的use,在这里做try-catch可以捕获所有错误
error(server);
loglib(server);

server.use(async (ctx, next) => {
    ctx.db = db;
    await next();
})

// post
server.use(convert(body({
    uploadDir: config.uploadDir
})))

// session
server.use(session({}, server));
server.keys = config.secret_key;

// 模板
ejs(server, {
    root: pathlib.resolve('./template'),
    layout: false,
    viewExt: '.ejs.html',
    cache: false,
    debug: false,
})

// 路由
const mainRouter = new Router();
mainRouter.use('/', require('./router/index'))
server.use(mainRouter.routes());

// 静态文件
server.use(staticCache(config.wwwDir));
